package com.aviccxzx.smarthome.UserModule;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.aviccxzx.smarthome.R;
import com.aviccxzx.smarthome.base.GosUserModuleBaseActivity;
import com.aviccxzx.smarthome.entity.GetMoveList;
import com.aviccxzx.smarthome.entity.SceneListAskBean;
import com.aviccxzx.smarthome.netutil.app.App;
import com.aviccxzx.smarthome.netutil.msg.MsgCenter;
import com.aviccxzx.smarthome.service.RetrofitHelper;
import com.aviccxzx.smarthome.service.RetrofitService;
import com.aviccxzx.smarthome.utils.DialogUtil;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.Timer;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * Created by joey on 2016/10/25.
 */
public class SceneDetailAct extends GosUserModuleBaseActivity implements View.OnClickListener{

    ListView move_list;
    MoveListAdapter adapter;
    ImageView add_move_img, edit_scene_img;
    String sceneId, sceneSwitch, sceneName = "";

    Timer mTimer;
    String uid, mac, imei;

    /**
     * 判断是否需要检测，防止不停的弹框
     */
    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 2:
                    adapter.notifyDataSetChanged();
                    break;
                default:
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setContentView(R.layout.scene_detail_lay_v19);
        } else {
        }
        initView();
        seListener();
        mTimer = new Timer();
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void seListener() {
        findViewById(R.id.ll_title_left_view).setOnClickListener(this);
        findViewById(R.id.add_scene_btn).setOnClickListener(this);

        add_move_img.setOnClickListener(this);
        edit_scene_img.setOnClickListener(this);

    }

    private void initView() {
        ((TextView) findViewById(R.id.title_tv)).setText("场景详情");
        add_move_img = (ImageView) findViewById(R.id.add_move_img);
        edit_scene_img = (ImageView) findViewById(R.id.edit_scene_img);

        move_list = (ListView) findViewById(R.id.move_list);
        sceneId = getIntent().getStringExtra("sceneId");
        sceneSwitch = getIntent().getStringExtra("sceneSwitch");
        sceneName = getIntent().getStringExtra("sceneName");

        adapter = new MoveListAdapter();
        move_list.setAdapter(adapter);
    }

    List<GetMoveList.DataBean> movelist = new ArrayList<>();

    public void getSceneList() {
        progressDialog.show();
        String uid = spf.getString("Uid", "");
        RetrofitService service = RetrofitHelper.getInstance(this).getServer();
        Call<GetMoveList> call = service.getSceneLogicList(sceneId, uid);
        call.enqueue(new Callback<GetMoveList>() {
            @Override
            public void onResponse(Call<GetMoveList> call, Response<GetMoveList> response) {
                if (response.body() != null && response.body().getData() != null)
                    movelist = response.body().getData();
                if (movelist != null && movelist.size() > 0) {
                    Message msg = new Message();
                    msg.what = 2;
                    handler.sendMessage(msg);
                    move_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                            Intent intent = new Intent(SceneDetailAct.this, MoveDetailAct.class);
                            intent.putExtra("tag", "moveList");
                            intent.putExtra("move_id", movelist.get(i).getScene_logic_id());
                            startActivity(intent);
                        }
                    });
                } else {
                    progressDialog.dismiss();
                    App.getApp().showToast("没有联动列表了");
                }
            }

            @Override
            public void onFailure(Call<GetMoveList> call, Throwable t) {
                progressDialog.dismiss();
            }
        });
    }


    @Override
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.ll_title_left_view:
                finish();
                break;
            case R.id.add_move_img:
                //添加动作
                intent = new Intent(this, MoveDetailAct.class);
                intent.putExtra("sceneID", sceneId);
                startActivity(intent);
                break;
            case R.id.add_scene_btn:
                //生成场景
                showToast("场景接口");
                break;
            case R.id.edit_scene_img:
                //场景编辑
                intent = new Intent(this, SetSceneAct.class);
                intent.putExtra("sceneId", sceneId);
                //                intent.putExtra("Switch",sceneSwitch);
                //                intent.putExtra("Name",sceneName);
                startActivity(intent);
                break;
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        getSceneList();
        movelist.clear();
    }




    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            this.finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }



    public class MoveListAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return movelist.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(final int i, View convertView, ViewGroup viewGroup) {
            View view = null;

            if (convertView != null) {
                view = convertView;
            } else {
                view = LayoutInflater.from(SceneDetailAct.this).inflate(R.layout.move_listitem_lay, viewGroup, false);
            }

            ViewHolder holder = (ViewHolder) view.getTag();
            if (holder == null) {
                holder = new ViewHolder();
                view.setTag(holder);
            }
            holder.move_list_delete = (ImageView) view.findViewById(R.id.move_list_delete);
            holder.device_img1 = (ImageView) view.findViewById(R.id.device_img1);
            holder.device_img2 = (ImageView) view.findViewById(R.id.device_img2);
            holder.move_item_name = (TextView) view.findViewById(R.id.move_item_name);

            holder.move_item_name.setText(movelist.get(i).getScene_logic_name());
            List<Integer> types = movelist.get(i).getDevice_types();
            int[] imgs = new int[]{R.mipmap.alarm_icon, R.mipmap.water_icon, R.mipmap.smoke_icon, R.mipmap.gas_icon, R.mipmap.door_icon, R.mipmap.video_icon};
            if (types.size() == 2) {
                if ((types.get(0) - 1)==2){
                    //烟感时 判断新旧
                    Set<String> newSmoke = spf.getStringSet("newSmoke", null);
                    if (newSmoke.contains(movelist.get(i).getConditionMac().toString().toUpperCase())){
                        //新烟感
                        holder.device_img1.setImageResource(R.mipmap.smoke_icon_hm); //图片资源
                    }else {
                        //旧烟感
                        holder.device_img1.setImageResource(imgs[types.get(0) - 1]); //图片资源
                    }
                    holder.device_img2.setImageResource(imgs[types.get(1) - 1]); //图片资源
                }else {

                    holder.device_img1.setImageResource(imgs[types.get(0) - 1]); //图片资源
                    holder.device_img2.setImageResource(imgs[types.get(1) - 1]); //图片资源
                }
            }

            holder.move_list_delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    new DialogUtil(SceneDetailAct.this, true, true, "确定要删除这个联动吗?", "取消", "确定", new DialogUtil.SureInterfance() {
                        @Override
                        public void sureTodo() {
                            RetrofitService service = RetrofitHelper.getInstance(SceneDetailAct.this).getServer();
                            Gson gson = new Gson();

                            String uid = spf.getString("Uid", "");
                            String Mac = spf.getString("gatemac", "");
                            String imei = spf.getString("Imei", "");

                            SceneListAskBean scene = new SceneListAskBean();
                            scene.setImei(imei);
                            scene.setMac(Mac);
                            scene.setUid(uid);

                            String strEntity = gson.toJson(scene);

                            RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), strEntity);
                            String id = movelist.get(i).getScene_logic_id();
                            Call<ResponseBody> call = service.deleteSceneLogic(body, id);
                            call.enqueue(new Callback<ResponseBody>() {
                                @Override
                                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                                    movelist.remove(movelist.get(i));
                                    notifyDataSetChanged();
                                    MsgCenter.fireNull("scene", "");
                                }

                                @Override
                                public void onFailure(Call<ResponseBody> call, Throwable t) {
                                    App.getApp().showToast("删除失败");
                                }
                            });
                        }

                        @Override
                        public void cancle() {

                        }
                    }).showCustomDialog();
                }
            });
            progressDialog.dismiss();

            return view;
        }

        public class ViewHolder {
            ImageView move_list_delete, device_img1, device_img2;
            TextView move_item_name;
        }
    }
}
